<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/17 14:43
 * Modified Time: 2019/7/17 14:43
 * Version: 2.0
 */

namespace App\Modules\Employee\Criterias;


use App\Lib\Utilities;
use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use Illuminate\Support\Facades\DB;

class GetStoreUserListCriteria extends BaseCriterias
{
    protected $store_id;

    public function __construct($store_id)
    {
        $this->store_id = $store_id;
    }

    public function apply($model, RepositoryInterface $repository)
    {
        $store_id = $this->store_id;

        $order_query = DB::table('order')
            ->selectRaw('count(*) as order_num,barber_id')
            ->where('store_id',$store_id)
            ->where('status',2)
            ->groupBy('barber_id');

        $comment_query = DB::table('order_comment')
            ->selectRaw('avg(score_store) as score,user_id')
            ->where('store_id',$store_id)
            ->groupBy('user_id');

        $select = [
            'hx_user.id',
            'hx_user.nick',
            'hx_picture.image',
            'IFNULL(hx_order.order_num,0) as order_num',
            'IFNULL(hx_comment.score,0) as score',
        ];
        $select = implode($select,',');

        $model = $model->selectRaw($select)
            ->leftJoin('user','user_store.uid','user.id')
            ->leftJoin('picture','user.portrait','picture.id')
            ->leftJoin(\DB::raw("({$order_query->toSql()}) as hx_order"), function ($join) use ($order_query) {
                $join->mergeBindings($order_query)->on('user.id','=', 'order.barber_id');
            })
            ->leftJoin(\DB::raw("({$comment_query->toSql()}) as hx_comment"), function ($join) use ($comment_query) {
                $join->mergeBindings($comment_query)->on('user.id','=', 'comment.user_id');
            })
            ->withCount(['order'=>function($v) use($store_id){
                $v->where(['store_id'=>$store_id,'status'=>2]);
            }])
            ->where('sid',$store_id)
            ->where('rid',2)
        ;

        return $model;
    }
}